using B.S.Requst;
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
using B.S.Domain.InvoiceManagement;
using B.S.Infratrctrue;

namespace B.S.Data.MES.API.Applications.B.S.KApplications.Command.InvoiceReceiptCommand
{
    /// <summary>
    /// 删除到票命令处理程序
    /// 处理到票信息的删除逻辑
    /// </summary>
    public class DeleteInvoiceReceiptCommandHandler : IRequestHandler<DeleteInvoiceReceiptCommand, APIRequst<bool>>
    {
        private readonly IBaseRepository<InvoiceReceipt> _invoiceReceiptRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="invoiceReceiptRepository">到票仓储</param>
        public DeleteInvoiceReceiptCommandHandler(IBaseRepository<InvoiceReceipt> invoiceReceiptRepository)
        {
            _invoiceReceiptRepository = invoiceReceiptRepository;
        }

        /// <summary>
        /// 处理删除到票的命令
        /// </summary>
        /// <param name="request">删除到票命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果，表示删除是否成功</returns>
        public async Task<APIRequst<bool>> Handle(DeleteInvoiceReceiptCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证参数
                if (request.ReceiptId <= 0)
                {
                    return new APIRequst<bool> { Code = RequstCode.失败, Msg = "到票记录ID不能为空" };
                }

                // 查找现有的到票记录
                var invoiceReceipt =  _invoiceReceiptRepository.GetAll().FirstOrDefault(s => s.ReceiptId == request.ReceiptId && !s.isDel);
                if (invoiceReceipt == null)
                {
                    return new APIRequst<bool> { Code = RequstCode.失败, Msg = "到票记录不存在" };
                }

                // 执行逻辑删除
                invoiceReceipt.isDel = true;
                invoiceReceipt.DeleteName = request.DeleteName;
                invoiceReceipt.DeleteTime = DateTime.Now;

                // 保存更新到数据库
                var result = await _invoiceReceiptRepository.Update(invoiceReceipt);
                if (result < 1)
                {
                    return new APIRequst<bool> { Code = RequstCode.失败, Msg = "删除到票记录失败" };
                }

                return new APIRequst<bool>
                {
                    Code = RequstCode.成功,
                    Msg = "删除到票记录成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                // 记录异常并返回失败结果
                return new APIRequst<bool>
                {
                    Code = RequstCode.失败,
                    Msg = $"删除到票记录失败：{ex.Message}"
                };
            }
        }
    }
}